package com.controller;

import com.model.Cart;
import com.model.Item;
import com.service.CartService;
import com.service.ItemService;
import com.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/cart",method = RequestMethod.POST)
public class CartRestController {
    @Autowired
    private CartService cartService;

    @Autowired
    private ItemService itemService;

//    @RequestMapping(value = "/id",method = RequestMethod.POST)
//    public List<Cart> getCartById(HttpServletRequest httpServletRequest){
//        String userid = (String)httpServletRequest.getSession().getAttribute("userid");
//        return cartService.getCartById(userid);
//    }

    @RequestMapping(value = "/",method = RequestMethod.POST)
    public List<CartVO> getCartBySessionId(HttpServletRequest httpServletRequest){
        Long userid = (Long)httpServletRequest.getSession().getAttribute("userid");
        //购物车内商品idList
        List<Cart> cartById = cartService.getCartByUserId(userid);
        //
        List<CartVO> res=new ArrayList<CartVO>();
        for(Cart cart:cartById){
            Long id = cart.getItemid();
            Item itemById = itemService.getItemById(id);
            String img=itemById.getImg();
            String itemname = itemById.getItemname();
            Integer price =itemById.getPrice();
            res.add(new CartVO(cart.getId(),img,itemname,price,cart.getQuantity()));
        }
        return res;
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public boolean addCartItem(Long itemid,HttpServletRequest httpServletRequest){
        Long userid= (Long) httpServletRequest.getSession().getAttribute("userid");
        boolean stus = cartService.addCartItem(userid, itemid, 1);
        return stus;
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public boolean DeleteCartItem(@RequestBody Map<String,Long> param){
        //Long userid= (Long) httpServletRequest.getSession().getAttribute("userid");
        Long cartid = param.get("cartid");
        return cartService.deleteCartItem(cartid);
    }

}
